package com.swak.service;

import java.io.Serializable;
import java.util.List;
import java.util.function.Consumer;

import com.swak.App;
import com.swak.entity.Page;
import com.swak.entity.Parameters;
import com.swak.persistence.QueryCondition;

/**
 * 封装了公用操作
 * 可以直接使用 AopContext.currentProxy() 获得代理对象
 * 
 * @author lifeng
 * @date 2020年4月17日 下午5:02:58
 */
public abstract class BaseService<T, PK extends Serializable> {

	private Object proxy;

	@SuppressWarnings("unchecked")
	protected <U> U getProxy() {
		if (this.proxy == null) {
			Class<?>[] interfacess = this.getClass().getInterfaces();
			if (interfacess != null && interfacess.length > 0) {
				this.proxy = App.getBean(interfacess[0]);
			} else {
				this.proxy = App.getBean(this.getClass());
			}
		}
		return (U) this.proxy;
	}

	protected void pageForConsumer(QueryCondition qc, Parameters param, Consumer<List<T>> consumer) {
		Page<T> page = this.pageByCondition(qc, param);
		int pageCount = page.getParam().getPageCount();
		for (int i = 1; i <= pageCount; i++) {
			consumer.accept(page.getData());
			param.setPageIndex(param.getPageIndex() + 1);
			page = this.pageByCondition(qc, param);
		}
	}

	protected Page<T> pageByCondition(QueryCondition query, Parameters param) {
		return null;
	}
}